﻿using System;
using System.Collections.Generic;
using System.Windows;
using Mongoose.Windows.Controls;

namespace Mongoose.Windows
{
    public class SurfaceWrapLayout : IPadContainerLayout
    {
        public SurfaceWrapLayout(Surface surface)
        {
            this.surface = surface;
        }

        /// <summary>
        /// Gets the surface.
        /// </summary>
        /// <value>
        /// The surface.
        /// </value>
        public Surface Surface
        {
            get { return surface; }
        }

        /// <summary>
        /// Gets a value indicating whether the pads should always be layouted or only when added to the surface.
        /// </summary>
        /// <value>
        /// <c>true</c> if this instance is dynamic; otherwise, <c>false</c>.
        /// </value>
        public bool IsDynamic
        {
            get { return false; }
        }

        /// <summary>
        /// Arranges the pads. Will be called whenever the pads collection on the surface changes.
        /// </summary>
        /// <param name="pads">The pads.</param>
        public void ArrangePads(IEnumerable<Pad> pads)
        {
            var surfaceWidth = surface.RenderSize.Width;
            var startingLeft = 10.0D;
            var currentLeft = startingLeft;
            var currentTop = 10.0D;
            var padMaxHeight = 0.0D;

            foreach (var pad in pads)
            {
                if (!pad.IsPinned)
                {
                    var currentPadSize = pad.RenderSize;

                    if (currentLeft + currentPadSize.Width > surfaceWidth)
                    {
                        currentLeft = startingLeft;
                        currentTop += padMaxHeight + 10;
                        padMaxHeight = 0.0D;
                    }

                    pad.Position = new Point(currentLeft, currentTop);
                    currentLeft += currentPadSize.Width + 10;
                    padMaxHeight = Math.Max(padMaxHeight, currentPadSize.Height);
                }
            }
        }

        IPadContainer IPadContainerLayout.Container
        {
            get { return Surface; }
        }

        #region Private members
        private Surface surface;
        #endregion 
    }
}
